#include "tcpserver.h"

using namespace std;

TCPserver::TCPserver()
{

}

void TCPserver::socket (char *argv[])
{
    sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(atoi(argv[1]));
    if (bind(sockfd, (struct sockaddr *) &serv_addr,
             sizeof(serv_addr)) < 0)
        error("ERROR on binding");
    listen(sockfd,5);
    clilen = sizeof(cli_addr);
}

void TCPserver::checkConnection(int argc)
{
    if (argc < 2)
    {
        cout<<"ERROR, falta el puerto"<<endl;
        exit(1);
    }
}

void TCPserver::conectar ()
{
    newsockfd = accept(sockfd,
                       (struct sockaddr *) &cli_addr, (socklen_t *) &clilen);
    if (newsockfd < 0)
        error("ERROR on accept");
}

void TCPserver::enviar (string buffer){

    bufferString2Char(buffer);
    n = write(newsockfd,cbuffer,strlen(cbuffer));
    if (n < 0) error("ERROR writing to socket");

}

void TCPserver::recibir ()
{
    bzero(ccbuffer,1024);
    n = read(newsockfd,ccbuffer,255);
    if (n < 0)
        error("ERROR reading from socket");
    bufferChar2String(ccbuffer);
}
